<?php
/**
 * 溢价管理模块
 */

namespace app\admin\controller\coupon;

use app\admin\controller\Controller;
use app\model\AgentConfig;
use app\model\CouponBrand;
use app\model\CouponProductChannel;
use app\Request;
use app\admin\validate\Coupon\Premium as PremiumValidate;
use app\model\CouponConfig;
use app\model\Agent;


class Premium extends Controller
{
    /**
     * 溢价设置
     * @access public
     * @method POST
     * @return \think\response\Json
     */
    public function setPremium(Request $request, PremiumValidate $validate)
    {
        $params = $request->param();
        //是否修改
        $id = $request->param('id');
        $type = $request->param('type');
        $config_type = $request->param('config_type')??0;
        $global = $request->param('global')??0;
        $agent_id = $request->param('agent_id')??0;
        $quote_id = $request->param('quote_id')??0;
        $premium_rate = $request->param('premium_rate');
        $status = $request->param('status')??CouponConfig::STATUS_ACTIVE;
        $result = $validate->scene('common')->check($params);
        if(!$result) {
            return fail($validate->getError());
        }
        if ($type == CouponConfig::CONFIG_TYPE_PTDG) { //全局溢价类型
            $result = $validate->scene('global')->check($params);
            if(!$result) {
                return fail($validate->getError());
            }
            if ($global == CouponConfig::GLOBAL_PTDLQJ || $global == CouponConfig::GLOBAL_DLQJ) {
                if (empty($agent_id)) {
                    return fail('为单个代理或者代理本身设置全局溢价，代理id不能为空');
                }
            }
        } else { //单个商品类型溢价设置
            $result = $validate->scene('config_set')->check($params);
            if(!$result) {
                return fail($validate->getError());
            }
            if ($config_type == CouponConfig::CONFIG_TYPE_PTDLDG || $config_type == CouponConfig::CONFIG_TYPE_DLDG) {
                if (empty($agent_id)) {
                    return fail('为单个代理或者代理本身设置全局溢价，代理id不能为空');
                }
            }
            if (empty($quote_id)) {
                return fail('为单个代理或者代理本身设置全局溢价，商品id不能为空');
            }
        }
        //验证代理
        if (!empty($agent_id)) {
            $agent = \app\model\Agent::where('id', $agent_id)->findOrEmpty();
            if ($agent->isEmpty()) {
                return fail('代理不存在');
            }
            //代理禁用......
            if ($agent->status == Agent::STATUS_CLOSE) {
                return fail('代理已被禁用');
            }
        }
        //验证商品
        if (!empty($quote_id)) {
            $productChannel = CouponProductChannel::where('id', $quote_id)->where('status', CouponProductChannel::STATUS_ACTIVE)->findOrEmpty();
            if ($productChannel->isEmpty()) {
                return fail('设置失败，商品不存在');
            }
            if ($productChannel->shelf_state != CouponProductChannel::SHELF_STATE_SZ) {
                return fail('设置失败，商品未上架');
            }
        }
        //$info = CouponConfig::where('id', $id)->where('status', CouponConfig::STATUS_ACTIVE)->findOrEmpty();
        $info = CouponConfig::where('id', $id)->findOrEmpty();
        if (!$info->isEmpty()) { //修改
            $info->agent_id     =   $agent_id;
            $info->quote_id     =   $productChannel->product_id;
            $info->config_type  =   $config_type;
            $info->global       =   $global;
            $info->status       =   $status;
            if ($status == 1) {
                $info->value        =   $premium_rate;
            }
            if (!$info->force()->save()) {
                return fail('溢价管理设置，修改失败');
            }
            return success('溢价管理设置成功');
        }
        $config = CouponConfig::findOrCreate([
            'agent_id'    => $agent_id,
            'quote_id'    => $productChannel->product_id,
            'config_type' => $config_type,
            'global'      => $global,
            'status'      => $status,
        ],[
            'value'       => $premium_rate
        ]);
        if ($config->id) {
            return success('溢价管理设置成功');
        }
        return fail('溢价管理设置失败');
    }

    /**
     * 溢价管理----默认模板管理列表
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function defaultTemp(Request $request)
    {
        $params = $request->only(['brand_name', 'keyWord', 'premium_type']);
        $params['config_type'] = CouponConfig::CONFIG_TYPE_PTDG;
        //查询品牌下的列表数据
        $list = (new CouponBrand())->getDefaultTempList($params);
        $map = [
            'global' => CouponConfig::GLOBAL_PTQJ,
            'status' => CouponConfig::STATUS_ACTIVE,
        ];
        //查询全局溢价设置
        $config = (new CouponConfig())->findConfigByParams($map);
        $list['global_config'] = $config;
        return  success('请求成功', $list);
    }

    /**
     * 溢价管理----代理商模板管理列表
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function agentTemp(Request $request)
    {
        $company_name = trim($request->param('company_name'));
        $mould = $request->param('mould');
        $list = (new Agent())->getAgentTempList($company_name, $mould);
        //查询全局溢价设置
        $map = [
            'global' => CouponConfig::GLOBAL_PTQJ,
            'status' => CouponConfig::STATUS_ACTIVE,
        ];
        $config = (new CouponConfig())->findConfigByParams($map);
        $list['global_config'] = $config;
        return  success('请求成功', $list);
    }

    /**
     * 溢价管理----编辑代理商溢价模板
     * @access public
     * @method get
     * @return \think\response\Json
     */
    public function editAgentTempList(Request $request)
    {
        $params = $request->only(['brand_name', 'keyWord', 'agent_id', 'mould', 'premium_type']);
        if (!in_array($mould = $params['mould'],[AgentConfig::MOULD_MR,AgentConfig::MOULD_ZDY])) {
            return fail('溢价模板参数错误');
        }
        //查询全局溢价设置
        if ($mould == AgentConfig::MOULD_MR) { // 默认模板
            $params['config_type'] = CouponConfig::CONFIG_TYPE_PTDG;
            $map = [
                'global' => CouponConfig::GLOBAL_PTQJ,
                'status' => CouponConfig::STATUS_ACTIVE,
            ];
        } else { // 自定义模板
            $params['config_type'] = CouponConfig::CONFIG_TYPE_PTDLDG;
            $map = [
                'global' => CouponConfig::GLOBAL_PTDLQJ,
                'status' => CouponConfig::STATUS_ACTIVE,
                'agent_id'  => $params['agent_id']
            ];
        }
        $list = (new CouponBrand())->getDefaultTempList($params);
        $config = (new CouponConfig())->findConfigByParams($map);
        $list['global_config'] = $config;
        //查询该代理的模板类型
        $agent = AgentConfig::where('agent_id', $params['agent_id'])->field('id,agent_id,mould')->findOrEmpty();
        $list['agent_config'] = !empty($agent->toArray())?$agent->toArray():null;
        return success('请求成功', $list);
    }

    /**
     * 溢价管理----平台代理商模板类型设置
     * @access public
     * @method post
     * @param int $tmeplate 模板类型
     * @return string
     */
    public function setAgentTemplate(Request $request)
    {
        $mould = $request->param('mould');
        $agent_id = $request->param('agent_id');
        if (!in_array($mould,[AgentConfig::MOULD_MR,AgentConfig::MOULD_ZDY])) {
            return fail('代理溢价模板参数错误');
        }
        $agent = Agent::where('id', $agent_id)->find();
        if (!$agent) {
            return fail('代理不存在');
        }
        AgentConfig::findOrCreate(
            ['agent_id' => $agent_id],
            [
                'mould' => $mould,
                'ali_public_key' => '',
                'ali_private_key' => '',
            ]
        );
        return success('设置模板类型成功', ['agent_id' => $agent_id, 'mould' => $mould]);
    }




}